/* list.c*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "list.h" 

// 局部函数原型
static void CopyToNode(Item item, Node * pnode);

void InitializeList(List * plist)
{
    * plist = NULL;
}

bool ListIsEmpty(List * plist)
{
    if (* plist == NULL)
        return true;
    else
        return false;
}

bool ListIsFull(List * plist)
{
    Node * pt;
    bool full;

    pt = (Node *)malloc(sizeof(Node));
    if (pt == NULL)   // 分配失败，返回false
        full = true;
    else
        full = false;
    free(pt);    // 将分配的内存释放
    return full;
}

unsigned int ListItemCount(const List * plist)
{
    unsigned int count = 0;
    Node * pnode = *plist; // 设置列表的开始处

    while(pnode != NULL)
    {
        ++count;
        pnode = pnode->next;  /* 设置下一个节点 */
    }
    return count;
}

bool AddItem(Item item, List * plist)
{
    Node * pnew;
    Node * scan = *plist;

    pnew = (Node *)malloc(sizeof(Node));
    if(pnew == NULL)
        return false;
    
    CopyToNode(item, pnew);   // 把传入的item结构赋值到新节点的item中
    pnew->next = NULL;  // 指向空指针
    if(scan == NULL)
        *plist = pnew;
    else
    {
        while(scan->next != NULL)
            scan = scan->next;  // 找到列表结尾
        scan->next = pnew;    // 新节点加到结尾
    }
    return true;
}

void Traverse(const List * plist, void (* pfun)(Item item))
{
    Node * pnode = * plist;
    while(pnode != NULL)
    {
        (*pfun)(pnode->item);    // 调用函数
        pnode = pnode->next;
    }
}

void EmptyTheList(List * plist)
{
    Node *psave;
    while(*plist != NULL)
    {
        psave = (*plist)->next;  // 保存下一个节点地址
        free(*plist);
        *plist = psave;    //前进到下一个节点
    }
}

// 局部函数定义
static void CopyToNode(Item item, Node * pnode)
{
    pnode->item = item;    // 结构复制
}